package login;

import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;
import common.model.User;

public class LoginService {
    public static final LoginService me = Duang.duang(LoginService.class);
    private static final User userDao = new User().dao();
    public static String USER = "username";

    public Ret login(String username, String pwd) {
        User user = userDao.findFirst(userDao.getSqlPara("user.findByUsername", username));
        if (null == user) {
            return Ret.by("status", false).set("msg", "用户不存在");
        }

        if (!pwd.equals(user.getPwd())) {
            return Ret.by("status", false).set("msg", "用户名密码错误");
        }
        String token = StrKit.getRandomUUID();
        Redis.use().set(token, user);
        return Ret.by("status", true).set("token", token);

    }

    public User validateToken(String token) {
        if (null == token) {
            return null;
        }
        User user = Redis.use().get(token);
        if (null == user) {
            return null;
        }
        return userDao.findById(user.getId());
    }
}
